package com.dzt.androidframework.database.addedittask;

import android.support.annotation.NonNull;
import android.support.annotation.Nullable;

import com.dzt.androidframework.database.javabean.Task;
import com.dzt.androidframework.database.tasks.TasksDataSource;
import com.dzt.androidframework.utils.JLogKit;

import static com.google.common.base.Preconditions.checkNotNull;

/**
 * Created by M02323 on 2017/6/12.
 */

public class AddEditPresenter implements AddEditContract.Presenter,
		TasksDataSource.GetTaskCallback{

	private final TasksDataSource tasksDataSource;
	private final AddEditContract.View addTaskView;
	private String taskId;
	private boolean isDataMissing;

	public AddEditPresenter(@Nullable String taskId,
								@NonNull TasksDataSource tasksRepository,
								@NonNull AddEditContract.View addTaskView,
								boolean shouldLoadDataFromRepo) {
		this.taskId = taskId;
		this.tasksDataSource = checkNotNull(tasksRepository);
		this.addTaskView = checkNotNull(addTaskView);
		isDataMissing = shouldLoadDataFromRepo;
	}
	
	@Override
	public void start() {
		if (!isNewTask() && isDataMissing) {
			populateTask();
		}
	}

	@Override
	public void saveTask(String title, String description) {
		if (isNewTask()) {
			createTask(title, description);
		} else {
			updateTask(title, description);
		}
	}

	@Override
	public void populateTask() {
		if (isNewTask()) {
			throw new RuntimeException("populateTask() was called but task is new.");
		}
		tasksDataSource.getTask(taskId, this);
	}

	@Override
	public boolean isDataMissing() {
		return isDataMissing;
	}

	@Override
	public void onTaskLoaded(Task task) {
		if (addTaskView.isActive()) {
			addTaskView.setTitle(task.getTitle());
			addTaskView.setDescription(task.getDescription());
		}
		isDataMissing = false;
	}

	@Override
	public void onDataNotAvailable() {
		if (addTaskView.isActive()) {
			addTaskView.showEmptyTaskError();
		}
	}

	private boolean isNewTask() {
		return taskId == null;
	}

	private void createTask(String title, String description) {
		Task newTask = new Task(title, description, false);
		if (newTask.isEmpty()) {
			addTaskView.showEmptyTaskError();
		} else {
			tasksDataSource.saveTask(newTask);
			addTaskView.showTasksList();
		}
	}

	private void updateTask(String title, String description) {
		if (isNewTask()) {
			throw new RuntimeException("updateTask() was called but task is new.");
		}
		Task task = new Task(title, description, taskId);
		tasksDataSource.updateTask(task);
		addTaskView.showTasksList(); // After an edit, go back to the list.
	}
}
